<template>
  <a-upload
    v-model:file-list="fileList"
    name="file"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="action"
    :before-upload="beforeUpload"
    :maxCount="1"
    :disabled="disabled"
    @change="handleChange"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar-uploader_img" alt="avatar" />
    <div v-else>
      <LoadingOutlined v-if="loading" style="font-size: 30px;color: #ffffff;" />
      <PlusOutlined v-else  style="font-size: 30px;color: #ffffff;" />
      <div class="ant-upload-text">{{ title ? title : $t("account.upload") }}</div>
    </div>
  </a-upload>
</template>
<script setup>
import { ref } from "vue";
import { message } from "ant-design-vue";
import {
  LoadingOutlined,
  PlusOutlined
} from '@ant-design/icons-vue';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

defineProps({
  title: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['success'])

const baseUrl = import.meta.env.VITE_APP_BASE_API
const action = ref(baseUrl + '/api/upload')

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref("");

const handleChange = (info) => {
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }
  if (info.file.status === "done") {
    console.log(info.fileList)
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, (base64Url) => {
      imageUrl.value = base64Url;
      loading.value = false;
      if(fileList.value[0].response.type == 'ok') {
        emits('success',fileList.value[0].response.message)
      }
    });
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG file!");
  }
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    message.error("Image must smaller than 20MB!");
  }
  return isJpgOrPng && isLt20M;
};

const setDefaultImg = (path) => {
  imageUrl.value = path
}

defineExpose({
  setDefaultImg
})

</script>
<style lang="scss" scoped>
.avatar-uploader > .ant-upload {
  width: 100%;
  height: 180px;
}
.avatar-uploader_img {
    width: 100%;
    height: 100%;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
:deep(.ant-upload-select) {
  width: 100% !important;
  height: 180px !important;
}
:deep(.ant-upload.ant-upload-select:not(.ant-upload-disabled):hover) {
  border-color: #d3b25b !important;
}
</style>